package com.myjoje.service.system;

import com.myjoje.base.BaseService;
import com.myjoje.bean.UserBean;
import com.myjoje.bean.system.DeptBean;
import com.myjoje.config.AppCache;
import com.myjoje.dao.system.DeptDao;
import com.myjoje.jpa.DeptJpa;
import com.myjoje.jpa.DeptStructureJpa;
import com.myjoje.util.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DeptService extends BaseService {


    @Autowired
    private DeptJpa deptJpa;

    @Autowired
    private DeptStructureJpa structureJpa;

    @Autowired
    private DeptDao deptDao;

    @Autowired
    private UserService userService;

    /**
     * 保存或更新部门
     */
    @Transactional
    public Message saveOrUpdateDept(DeptBean bean, String userIds) {
        if (isEmpty(bean.getId())) {
            return saveDept(bean, userIds);
        } else {
            return updateDept(bean, userIds);
        }
    }

    /**
     * 更新部门
     */
    private Message updateDept(DeptBean bean, String userIds) {
        String id = bean.getId();
        DeptBean oldBean = (DeptBean) getDeptById(id).getData();
        //先移除旧的管理员
        String oldAdminIds = oldBean.getAdminIds();
        if (isNotEmpty(oldAdminIds)) {
            String[] arr = oldAdminIds.split(",");
            for (int i = 0; i < arr.length; i++) {
                String userId = arr[i];
                userService.deleteUserDept(userId, id);
            }
        }

        String name = bean.getName();
        //部门名称相同
        if (!oldBean.getName().equals(name)) {
            if (deptJpa.countByName(name) > 0) {
                return Message.error("部门名称已经存在");
            }
        }
        bean.setModifyTime(getDateTime());
        bean.setModifyUser(getCurrentUserId());
        deptJpa.save(bean);

        //更新指定用户的部门
        updateUserDept(userIds, bean.getId());

        return Message.success("更新成功");
    }

    private void updateUserDept(String userIds, String deptId) {
        if (isNotEmpty(userIds)) {
            String[] arr = userIds.split(",");
            for (int i = 0; i < arr.length; i++) {
                String userId = arr[i];
                userService.addUserDept(userId, deptId);
            }
        }
    }

    /**
     * 保存部门
     */
    public Message saveDept(DeptBean bean, String userIds) {
        String name = bean.getName();
        if (deptJpa.countByName(name) > 0) {
            return Message.error("部门名称已经存在");
        }
        bean.setCreateTime(getDateTime());
        bean.setCreateUser(getCurrentUserId());
        deptJpa.save(bean);

        //更新超级管理员
        updateRootDeptIds();

        //更新指定用户的部门
        updateUserDept(userIds, bean.getId());
        return Message.success("保存成功");
    }

    //更新超级管理员部门ids
    private void updateRootDeptIds() {
        //为超级管理员添加部门id
        List<DeptBean> deptList = deptJpa.findAll();
        //将所有的机构id拼接成字符串
        String deptIds = deptList.stream().map(DeptBean::getId).collect(Collectors.joining(","));
        userService.updateRootDeptIds(deptIds);
    }

    /**
     * 部门列表
     */
    public List<DeptBean> getDeptList(Integer currentPage, Integer pageSize) {
        List<DeptBean> list = deptDao.get(currentPage, pageSize);
        //查询部门的管理员
        for (DeptBean bean : list) {
            //获取部门管理人信息
            List<UserBean> userList = userService.getUserListByRoleAndDept(AppCache.getRoleAdmin(), bean.getId());
            String adminNames = userList.stream().filter(user -> {
                return !user.getUsername().equals("admin");
            }).map(UserBean::getNickname).collect(Collectors.joining(","));
            bean.setAdminNames(adminNames);
        }
        return list;
    }

    /**
     * 部门数量
     */
    public Long getDeptCount() {

        return deptDao.getCount(null);
    }

    /**
     * 删除部门
     *
     * @param id
     * @return
     */
    @Transactional
    public Message deleteDept(String id) {
        Long count = userService.getUserCountByDeptId(id);
        if (count <= 1) {
            //删除部门
            deptJpa.deleteById(id);
            //更新超级管理员部门
            updateRootDeptIds();
            return Message.success("删除成功");
        } else {
            return Message.error("删除失败");
        }
    }

    /**
     * 根据id获取部门
     */
    public Message getDeptById(String id) {
        //部门信息
        DeptBean bean = deptJpa.getOne(id);
        //获取部门管理人信息
        List<UserBean> list = userService.getUserListByRoleAndDept(AppCache.getRoleAdmin(), id);
        String adminIds = list.stream().filter(user -> {
            return !user.getUsername().equals("admin");
        }).map(UserBean::getId).collect(Collectors.joining(","));
        bean.setAdminIds(adminIds);
        return Message.success("请求成功", bean);
    }

    /**
     * 获取所有部门
     */
    public Object getAllDept() {
        return Message.success("请求成功", deptDao.get(null, null));
    }

    public List<DeptBean> getDeptByIds(HashSet<String> ids) {
        return deptJpa.findByIdIn(ids);
    }
}
